//
//  AddRealCustomerVC.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/6/4.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "AddRealCustomerVC.h"
#import "AddCustomerCell.h"
#import "EditCustomerCell2.h"
#import "EditCustomerCell3.h"
#import "BrokerDataMange.h"
#import "AddRealCusModel.h"
#import "LoginDataMange.h"
#import "StringTool.h"
#import "MBProgressHUD+MJ.h"
#import "BingPremiseVc.h"
#import "UserModal.h"
#import "config.h"
#import "UIView+circular.h"

@interface AddRealCustomerVC ()<UITableViewDataSource,UITableViewDataSource,BingPremiseVcDelegate,UITextFieldDelegate,UIScrollViewDelegate>

@property (nonatomic,strong)NSArray *dataArray;

@property (strong, nonatomic) BrokerDataMange *dataMange;
@property (strong, nonatomic) AddRealCusModel *model;
@property (strong, nonatomic) LoginDataMange *cpathaDM;//短信验证码

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic,strong)AddCustomerCell *cell1;


@property (nonatomic,assign)NSInteger timeout;
@property (nonatomic,assign)BOOL btnEnable;
@property (nonatomic,strong) NSTimer *timer;

@property (nonatomic,strong) EditCustomerCell2 *cell2;


@end

@implementation AddRealCustomerVC

@synthesize cell1,cell2,timer;


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
}

-(void)addTimer;
{
    self.timeout = 60;
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(Countdown) userInfo:nil repeats:YES];
    
}

-(void)initView
{
    self.titleView.doneBtn.hidden = YES;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (self.state == isAddCustomer) {
        [self.titleView setMianTitle:@"添加客户"];
    }else if (self.state == isLanteToRealCustomer)
    {
        [self.titleView setMianTitle:@"转为真实客户"];
    }
    
    
}

-(BrokerDataMange *)dataMange
{
    if (!_dataMange) {
        _dataMange = [[BrokerDataMange alloc]init];
    }
    return _dataMange;
}

-(AddRealCusModel *)model
{
    if (!_model) {
        _model = [[AddRealCusModel alloc]init];
    }
    return _model;
}

-(LoginDataMange *)cpathaDM
{
    if (!_cpathaDM) {
        _cpathaDM = [[LoginDataMange alloc]init];
    }
    return _cpathaDM;
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count + 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        cell1 =  [AddCustomerCell cellWithTableView:tableView];
        
        if (self.state == isLanteToRealCustomer) {
            cell1.latenModel = self.latenModel;
        }
        cell1.lockBtn.tag = 1;
        [cell1.lockBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        cell1.yanzhengBtn.tag = 0;
        [cell1.yanzhengBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        cell1.nameTextField.delegate = self;
        cell1.pwdTextField.delegate = self;
        cell1.yanZhengCodeTextField.delegate = self;
        cell1.pwdTextField.delegate = self;
        cell1.repeatPwdTextField.delegate = self;
        cell1.phoneTextField.delegate = self;
        
        return cell1;
    }else if (indexPath.row == self.dataArray.count + 1)
    {
        cell2 = [EditCustomerCell2 cellWithTableView:tableView];
        cell2.saveBtn.tag = 2;
        [cell2.saveBtn viewToCircular];
        [cell2.saveBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        return cell2;
    }else
    {
        EditCustomerCell3 *cell = [EditCustomerCell3 cellWithTableView:tableView];
        cell.model = [self.dataArray objectAtIndex:indexPath.row - 1];
        
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return [AddCustomerCell getHeight];
    }else if (indexPath.row == self.dataArray.count + 1)
    {
        return [EditCustomerCell2 getHeight];
    }else
    {
        return 44;
    }
}


#pragma mark 效验手机号
-(BOOL)checkPhone
{
    if ([StringTool isBlankString:cell1.phoneTextField.text]) {
        [MBProgressHUD showError:@"请输入手机号"];
        return NO;
    }else
    {
        if (![self validateMobile:cell1.phoneTextField.text]) {
            [MBProgressHUD showError:@"请输入正确的手机号"];
            return NO;
        }
    }
    return YES;
}
#pragma mark 检查密码
-(BOOL)chekcPwd
{
    if ([StringTool isBlankString:cell1.pwdTextField.text]) {
        [MBProgressHUD showError:@"请输入密码"];
        return NO;
    }else if ([StringTool isBlankString:cell1.repeatPwdTextField.text])
    {
        [MBProgressHUD showError:@"请输入确认密码"];
        return NO;
    }else if (![cell1.pwdTextField.text isEqualToString:cell1.repeatPwdTextField.text])
    {
        [MBProgressHUD showError:@"两次密码输入不一致"];
        return NO;
    }
    return YES;
}
#pragma mark 点击按钮
- (void)clickBtn:(UIButton *)sender
{
    NSInteger tag = sender.tag;
    switch (tag) {
        case 0://验证码
        {
            if ([self checkPhone]) {
                
                [self getCpatch];
            }
        }
            break;
        case 1://绑定楼盘
        {
            BingPremiseVc *vc = [[BingPremiseVc alloc]initWithNibName:@"BingPremiseVc" bundle:nil];
            vc.coustomerCode = [UserModal shareUserModel].userCode;
            vc.vcState = PREVIOUSVC_ADDCUS;
            vc.delegate = self;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2://保存信息
            if ([self checkInfo])
            {
                [self updata];
            }
            
            break;
            
        default:
            break;
    }
}
#pragma mark 检查输入信息
-(BOOL)checkInfo
{
    if ([StringTool isBlankString:cell1.nameTextField.text])
    {
        [MBProgressHUD showError:@"客户姓名为空!"];
        return NO;
    }else if (![self checkPhone])
    {
        return NO;
    }else if (![self chekcPwd])
    {
        return NO;
    }else if ([StringTool isBlankString:[UserModal shareUserModel].premiseIds])
    {
        [MBProgressHUD showError:@"请绑定楼盘"];
        return NO;
    }
    self.model.premisesIds = [StringTool isBlankString:[UserModal shareUserModel].premiseIds]?@"":[UserModal shareUserModel].premiseIds ;
    self.model.name = cell1.nameTextField.text;
    self.model.mobile = cell1.phoneTextField.text;
    self.model.captch = cell1.yanZhengCodeTextField.text;
    self.model.password = cell1.pwdTextField.text;
    self.model.repassword = cell1.repeatPwdTextField.text;
    
    return YES;
}
#pragma mark 获取短信验证码
-(void)getCpatch
{
    
    [self addTimer];

    __weak typeof(self)bself = self;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        ResulteMod *mod = [bself.dataMange addconsumercaptcha:cell1.phoneTextField.text];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (mod.resltState == ResultFail) {
                [MBProgressHUD showError:mod.resultTip];

                if ([mod.resultCode isEqualToString:@"20001"]) {
                    [timer invalidate];
                    [cell1.yanzhengBtn setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
                    cell1.yanzhengBtn.enabled = YES;
                    
                }
            }else if (mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                [MBProgressHUD showSuccess:@"验证码已发送，注意查收"];
            }
        });
    });
}

#pragma mark 提交数据
-(void)updata
{
    [MBProgressHUD showMessage:@"请操作" toView:self.view];
    __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *customerId = [NSString stringWithFormat:@"%zd",[UserModal shareUserModel].userId];
        NSString *potentialId;
        if (bself.state == isAddCustomer) {
            potentialId = @"0";
        }else if (bself.state == isLanteToRealCustomer && bself.latenModel != nil)
        {
            potentialId = bself.latenModel.consumerId;
        }
        ResulteMod *mod = [bself.dataMange addconsumerWithCustmerModel:bself.model withCustomerId:customerId withpotentialId:potentialId];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            [bself.nav popViewControllerAnimated:YES];
            
            if (mod.resltState == ResultFail) {
                
                [MBProgressHUD showError:mod.resultTip];
            }else if (mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                if (bself.state == isAddCustomer) {
                    [MBProgressHUD showSuccess:@"添加成功"];
                }else if (bself.state == isLanteToRealCustomer)
                {
                    [MBProgressHUD showSuccess:@"转为真实客户成功"];
                   
                }
                
            }
            
        });
    });
}

#pragma mark bingpremiseVC的代理
-(void)bingPremiseVcSeletedSitesArr:(NSArray *)premisesArr
{
    self.dataArray = [[NSArray alloc]initWithArray:[UserModal shareUserModel].editLockSiteArr];
    [self.tableView reloadData];
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    
    CGRect dd =  [textField.superview convertRect:textField.frame toView:self.tableView];
    
    int tvbotY = dd.size.height+dd.origin.y;
    int mid  = PMH-250-tvbotY-40;
    
    if (mid<0&&up==true) {
        
        const float movementDuration = 0.3f;
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        
        CGRect buf = self.view.frame;
        buf.origin.y = up ? mid : 0;
        [self.tableView setFrame:buf];
        
        [UIView commitAnimations];
    }else if(up==false){
        
        [self viewRest];
    }
}


-(void)viewRest{
    
    
    const float movementDuration = 0.3f;
    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    
    CGRect buf = self.tableView.frame;
    buf.origin.y =  0;
    [self.tableView setFrame:buf];
    
    [UIView commitAnimations];
    
    [self.tableView endEditing:YES];
}

#pragma et delegare
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self animateTextField:textField up:false];
    
    [textField resignFirstResponder];
    
    [self viewRest];
    return  YES;
}

#pragma mark scrollVIew delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self viewRest];
}




#pragma mark 验证码倒计时
-(void)Countdown
{

    
    [cell1.yanzhengBtn setTitle:[NSString stringWithFormat:@"%zd重新获取",self.timeout] forState:UIControlStateNormal];
    cell1.yanzhengBtn.enabled = NO;
    self.timeout --;
    if (self.timeout < 0) {
        [timer invalidate];
        [cell1.yanzhengBtn setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
        cell1.yanzhengBtn.enabled = YES;
    }
    
    
}

@end
